// 登录模块
const { Controller } = require('egg')

const Response = require('../utils/Response')

class UserLogon extends Controller {
  // 登录
  async logon() {
    const { ctx, service, app } = this
    // 1、获取前端参数
    const accountData = ctx.request.body
    // 2、调用service层操作数据库
    const userInfo = await service.logon.logon(accountData)
    // 示例
    if (userInfo) {
      const token =
        'Bearer ' +
        this.app.jwt.sign({ username: accountData.username }, this.app.config.jwt.secret, { expiresIn: '6000s' })
      ctx.body = new Response('登录成功', 200, userInfo)
      ctx.body.token = token
    }
  }

  // 注册
  async register() {
    const { ctx, service } = this
    // 获取参数
    const userInfo = ctx.request.body
    // 调用service层方法
    const message = await service.logon.register(userInfo)
    if (message === 1) {
      ctx.body = new Response('注册成功')
    } else {
      ctx.body = new Response('用户已存在，请直接登录')
    }
  }
}
module.exports = UserLogon
